package com.ytjj.qmyx.admin.controller.data;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.eunm.ActivityTypeEnums;
import com.ytjj.qmyx.admin.eunm.ActivityTypeNameCode;
import com.ytjj.qmyx.admin.model.request.UserStatisticsRequest;
import com.ytjj.qmyx.admin.model.request.bankerProduct.NewStatisticsRequest;
import com.ytjj.qmyx.admin.model.request.dataStatistics.ReturnOrderStatisticsRequest;
import com.ytjj.qmyx.admin.model.response.statistics.AllNewStatisticsResponse;
import com.ytjj.qmyx.admin.model.response.statistics.NewStatisticsResponse;
import com.ytjj.qmyx.admin.model.response.statistics.ReturnGoodStatisticsDetailResponse;
import com.ytjj.qmyx.admin.model.response.statistics.ReturnGoodStatisticsSearchResponse;
import com.ytjj.qmyx.admin.service.data.NewStatisticsService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @Description 新统计
 * @ClassName NewStatisticsController
 *
 * 
 * @Version 1.0
 **/

@RestController
@RequestMapping("/newStatistics")
@RefreshScope
@Slf4j
public class NewStatisticsController {

    @Resource
    private NewStatisticsService newStatisticsService;
    /**
     * 用户限制开关  1-打开 0-关闭
     */
    @Value("${statistics.user.limit:0}")
    private Integer statisticsUserLimit;

    @Resource
    private SupplyApiConfig supplyApiConfig;

    Executor pools = new ThreadPoolExecutor(5, 10, 5,TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

    /**
     * 新统计-总
     * @param newStatisticsRequest
     * @returngetAllStatistics
     */
    @PostMapping("/getAllStatistics")
    public CommonResult getAllStatistics(@RequestBody NewStatisticsRequest newStatisticsRequest) {
        //管理员可以看汇总
        String email= UserUtil.getPrincipal();
        newStatisticsRequest.setUserid(email);
        if (StringUtils.isEmpty(newStatisticsRequest.getActivityType())) {
            if(UserUtil.isAdmin()){
                newStatisticsRequest.setShowTotal(true);
            }else{
                newStatisticsRequest.setShowTotal(false);
            }
        }else {
            newStatisticsRequest.setShowTotal(true);
        }
        if (0 == statisticsUserLimit) {
            newStatisticsRequest.setShowTotal(true);
        }
        if (StringUtils.isNotBlank(newStatisticsRequest.getStartDate()) && StringUtils.isNotBlank(newStatisticsRequest.getEndDate())) {
            DateTime beginDate = DateUtil.parse(newStatisticsRequest.getStartDate(), "yyyy-MM-dd");
            DateTime endDate = DateUtil.parse(newStatisticsRequest.getEndDate(), "yyyy-MM-dd");
            long between = DateUtil.between(beginDate, endDate, DateUnit.DAY);
            if (between > 31) {
                throw new ApiException("查询时间跨度不能超过31天");
            }
        }

        return CommonResult.success(newStatisticsService.getAllStatistics(newStatisticsRequest));
    }

    /**
     * 财务汇总统计导出
     * @return
     */
    @PostMapping("/financialExport")
    public CommonResult financialExport(@RequestBody NewStatisticsRequest newStatisticsRequest){
        if (StringUtils.isNotBlank(newStatisticsRequest.getStartDate()) && StringUtils.isNotBlank(newStatisticsRequest.getEndDate())) {
            DateTime beginDate = DateUtil.parse(newStatisticsRequest.getStartDate(), "yyyy-MM-dd");
            DateTime endDate = DateUtil.parse(newStatisticsRequest.getEndDate(), "yyyy-MM-dd");
            long between = DateUtil.between(beginDate, endDate, DateUnit.DAY);
            if (between > 31) {
                throw new ApiException("查询时间跨度不能超过31天");
            }
        }
        return CommonResult.success(newStatisticsService.getFinancialExport(newStatisticsRequest));
    }

    /**
     * 新统计-导出选择的渠道分别统计
     * @param newStatisticsRequest
     * @returngetAllStatistics
     */
    @PostMapping("/getStatisticsItems")
    public CommonResult<List<NewStatisticsResponse>> getStatisticsItems(@RequestBody NewStatisticsRequest newStatisticsRequest) {
        //管理员可以看汇总
        String email= UserUtil.getPrincipal();
        newStatisticsRequest.setUserid(email);
        if (StringUtils.isEmpty(newStatisticsRequest.getActivityType())) {
            if(UserUtil.isAdmin()){
                newStatisticsRequest.setShowTotal(true);
            }else{
                newStatisticsRequest.setShowTotal(false);
            }
        }else {
            newStatisticsRequest.setShowTotal(true);
        }
        if (0 == statisticsUserLimit) {
            newStatisticsRequest.setShowTotal(true);
        }
        String channel = StringUtils.deleteWhitespace(newStatisticsRequest.getChannel());
        if(StringUtils.isEmpty(channel)){
            throw new ApiException("请选择渠道后再导出！");
        }

        if (StringUtils.isNotBlank(newStatisticsRequest.getStartDate()) && StringUtils.isNotBlank(newStatisticsRequest.getEndDate())) {
            DateTime beginDate = DateUtil.parse(newStatisticsRequest.getStartDate(), "yyyy-MM-dd");
            DateTime endDate = DateUtil.parse(newStatisticsRequest.getEndDate(), "yyyy-MM-dd");
            long between = DateUtil.between(beginDate, endDate, DateUnit.DAY);
            if (between > 31) {
                throw new ApiException("导出时间跨度不能超过31天");
            }
        }

        List<String> channelList = Arrays.asList(channel.split(","));
//        CountDownLatch countDownLatch = new CountDownLatch(channelList.size());
        List<NewStatisticsResponse> statistic = new ArrayList<>();
        channelList.stream().forEach(item->{
            try {
                newStatisticsRequest.setChannel(item);
                AllNewStatisticsResponse allStatistics = newStatisticsService.getAllStatistics(newStatisticsRequest);
                NewStatisticsResponse sumNewStatisticsResponse = allStatistics.getSumNewStatisticsResponse();
                sumNewStatisticsResponse.setChannel(item);
                statistic.add(sumNewStatisticsResponse);
            } catch (Exception e) {
                log.error("查询统计渠道出错===》{}",e);
            }
        });

//        channelList.stream().forEach(item->{
//            pools.execute(()->{
//                try {
//                    newStatisticsRequest.setChannel(item);
//                    AllNewStatisticsResponse allStatistics = newStatisticsService.getAllStatistics(newStatisticsRequest);
//                    NewStatisticsResponse sumNewStatisticsResponse = allStatistics.getSumNewStatisticsResponse();
//                    sumNewStatisticsResponse.setChannel(item);
//                    statistic.add(sumNewStatisticsResponse);
//                } catch (Exception e) {
//                    log.error("查询统计渠道出错===》{}",e);
//                }finally {
//                    countDownLatch.countDown();
//                }
//            });
//        });
//        try {
//            countDownLatch.await();
//        } catch (Exception e) {
//            log.error("===查询分别统计渠道出错==={}", e);
//        }
        //按channel输入的顺序排序
        List<NewStatisticsResponse> result = new ArrayList<>();
        for (String item : channelList) {
            List<NewStatisticsResponse> collect = statistic.stream().filter(e -> item.equals(e.getChannel())).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(collect)){
                result.add(new NewStatisticsResponse());
                continue;
            }
            result.add(collect.get(0));
        }
        return CommonResult.success(result);
    }


    /**
     * 新统计-总 new
     * @param newStatisticsRequest
     * @returngetAllStatistics
     */
    @PostMapping("/getNewAllStatistics")
    public CommonResult getNewAllStatistics(@RequestBody NewStatisticsRequest newStatisticsRequest) {
        //管理员可以看汇总
        String email= UserUtil.getPrincipal();
        newStatisticsRequest.setUserid(email);
        if (StringUtils.isEmpty(newStatisticsRequest.getActivityType())) {
            if(UserUtil.isAdmin()){
                newStatisticsRequest.setShowTotal(true);
            }else{
                newStatisticsRequest.setShowTotal(false);
            }

        }else {
            newStatisticsRequest.setShowTotal(true);
        }
        if (0 == statisticsUserLimit) {
            newStatisticsRequest.setShowTotal(true);
        }
        newStatisticsRequest.setIsCost(1);
        if (StringUtils.isNotBlank(newStatisticsRequest.getStartDate()) && StringUtils.isNotBlank(newStatisticsRequest.getEndDate())) {
            DateTime beginDate = DateUtil.parse(newStatisticsRequest.getStartDate(), "yyyy-MM-dd");
            DateTime endDate = DateUtil.parse(newStatisticsRequest.getEndDate(), "yyyy-MM-dd");
            long between = DateUtil.between(beginDate, endDate, DateUnit.DAY);
            if (between > 31) {
                throw new ApiException("查询时间跨度不能超过31天");
            }
        }
        return CommonResult.success(newStatisticsService.getAllStatistics(newStatisticsRequest));
    }


    /**
     * 活动新统计
     * @param newStatisticsRequest
     * @return
     */
    @PostMapping("/getActivityStatistics")
    public CommonResult getActivityStatistics(@RequestBody NewStatisticsRequest newStatisticsRequest) {
        if(StringUtils.isBlank(newStatisticsRequest.getActivityType())){
            newStatisticsRequest.setActivityType(ActivityTypeNameCode.COMMON.getCode());
        }
        return CommonResult.success(newStatisticsService.getAllStatistics(newStatisticsRequest));
    }

    /**
     * 用户下单数统计
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    @GetMapping("/getPayNumForUserStatistics")
    public CommonResult<Map<String,Object>> getPayNumForUserStatistics(String startTime,String endTime){
        Map<String, Object> payNumForUserStatistics = newStatisticsService.getPayNumForUserStatistics(startTime, endTime);
        return CommonResult.success(payNumForUserStatistics);
    }

    /**
     * 用户分析统计
     * @return
     */
    @PostMapping("/getUserAnalysis")
    public CommonResult getUserAnalysis(@RequestBody UserStatisticsRequest userStatisticsRequest){
        return CommonResult.success(newStatisticsService.getUserAnalysis(userStatisticsRequest));
    }

    /**
     * 执行单品售后统计
     */
    @PostMapping("/doProductRefundStatistics")
    public CommonResult doProductRefundStatistics(@RequestBody ReturnOrderStatisticsRequest orderStatisticsResponses) {
        String startTime = orderStatisticsResponses.getStartTime();
        String endTime = orderStatisticsResponses.getEndTime();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(startTime) && org.apache.commons.lang3.StringUtils.isNotBlank(endTime)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime1 = LocalDateTime.parse(startTime, formatter);
            LocalDateTime dateTime2 = LocalDateTime.parse(endTime, formatter);
            long daysBetween = ChronoUnit.DAYS.between(dateTime1, dateTime2);
            if (daysBetween > 90) {
                throw new ApiException("查询时间跨度不能超过90天");
            }
        } else {
            throw new ApiException("开始时间和结束时间不能为空！");
        }
        String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/doProductRefundStatistics", JSON.toJSONString(orderStatisticsResponses), supplyApiConfig.getHeadsMap());
        if(StringUtils.isNotEmpty(result)){
            return JSON.parseObject(result, CommonResult.class);
        }else {
            return CommonResult.failed("接口异常！");
        }
    }

    /**
     * 单品退单统计-统计详情
     * @param markId 统计的标识
     * @param pageNum 当前页
     * @param pageSize 每页条数
     */
    @GetMapping("/getProductRefundStatisticsDetail")
    public CommonResult<CommonPage<ReturnGoodStatisticsDetailResponse>> getProductRefundStatisticsDetail(String markId, Integer pageNum, Integer pageSize) {
        Map<String,String> requstMap = new HashMap<>();
        requstMap.put("markId",markId);
        requstMap.put("pageNum",String.valueOf(pageNum));
        requstMap.put("pageSize",String.valueOf(pageSize));
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getProductRefundStatisticsDetail", requstMap, supplyApiConfig.getHeadsMap());
        if(StringUtils.isNotEmpty(result)){
            return JSON.parseObject(result, CommonResult.class);
        }else {
            return CommonResult.failed("接口异常！");
        }
    }

    /**
     * 单品退单统计-统计详情汇总
     * @param markId 统计的标识
     */
    @GetMapping("/getProductRefundStatisticsSummary")
    public CommonResult<ReturnGoodStatisticsDetailResponse> getProductRefundStatisticsSummary(String markId) {
        Map<String,String> requstMap = new HashMap<>();
        requstMap.put("markId",markId);
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getProductRefundStatisticsSummary", requstMap, supplyApiConfig.getHeadsMap());
        if(StringUtils.isNotEmpty(result)){
            return JSON.parseObject(result, CommonResult.class);
        }else {
            return CommonResult.failed("接口异常！");
        }
    }

    /**
     * 分页单品退单统计历史
     * @param pageNum 当前页
     * @param pageSize 每页条数
     */
    @GetMapping("/getHistoryProductRefund")
    public CommonResult<CommonPage<ReturnGoodStatisticsSearchResponse>> getHistoryProductRefund(Integer pageNum, Integer pageSize) {
        Map<String,String> requstMap = new HashMap<>();
        requstMap.put("pageNum",String.valueOf(pageNum));
        requstMap.put("pageSize",String.valueOf(pageSize));
        String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/returnGoods/getHistoryProductRefund", requstMap, supplyApiConfig.getHeadsMap());
        if(StringUtils.isNotEmpty(result)){
            return JSON.parseObject(result, CommonResult.class);
        }else {
            return CommonResult.failed("接口异常！");
        }
    }

}